package com.bops.valve;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.bops.biz.permission.GrantManager;
import com.bops.biz.permission.UserGrant;
import com.bops.valve.webuser.BopsWebUser;
import com.bops.valve.webuser.BopsWebUserBuilder;
import com.yue.commons.seine.web.pipeline.AbstractPipelineValves;
import com.yue.commons.seine.web.pipeline.PipelineMap;
import com.yue.commons.seine.web.pipeline.PipelineResult;

public class BopsWebUserBuilderValve  extends AbstractPipelineValves {
    
    private List<String> noCheckUrlList = new ArrayList<String>();
    private List<String> noCheckUrlLikeList;

    public PipelineResult invoke(HttpServletRequest request, HttpServletResponse response, PipelineMap map) throws Exception {
        
        String uri = request.getRequestURI();
        HttpSession session = request.getSession();
        Integer userId = (Integer) session.getAttribute("bopsUserId");
        if (noCheckUrlList!=null && noCheckUrlList.contains(uri) && userId ==null )
        {
            return null;
        }
        if (noCheckUrlLikeList!=null && userId ==null )
        {
            for (String s:noCheckUrlLikeList)
            {
                int index = s.lastIndexOf("*");
                if (index!=-1)
                {
                    s = s.substring(0,index);
                    if (uri.startsWith(s))
                    {
                        return null;
                    }
                }
            }
        }
       
        BopsWebUser bopsWebUser = BopsWebUserBuilder.createBopsWebUser(userId);
        boolean canAccess = bopsWebUser.hasLogin();
        
        if (canAccess)
        {
            UserGrant userGrant = GrantManager.getUserGrant(bopsWebUser.getMemberId(),bopsWebUser.getRoleList());
            bopsWebUser.setUserGrant(userGrant);
            if (userGrant==null || !userGrant.checkUserGrant(uri, request)) {
                System.out.println(uri+" 没有权限");
                //return PipelineResult.gotoFinally("gotoLogin","/role/nopermission.htm");
            }
            return null;
        }
        else
        {
            return PipelineResult.gotoFinally("gotoLogin","/index.htm");
        } 
    }
    
    public List<String> getNoCheckUrlList() {
        return noCheckUrlList;
    }

    public void setNoCheckUrlList(List<String> noCheckUrlList) {
        this.noCheckUrlList = noCheckUrlList;
    }

    static Long parserLong(String number) {
        try {
            return Long.parseLong(number);
        } catch (NumberFormatException e) {
            return null;
        }
    }
    
    
    public void setNoCheckUrlLikeList(List<String> noCheckUrlLikeList) {
        this.noCheckUrlLikeList = noCheckUrlLikeList;
    }

}
